const express = require('express')
const request = require('superagent')
const router = express.Router()
const fs = require('fs')
const galleryListParser = require('./../parser/galleryListParser')
const galleryDetailParser = require('./../parser/galleryDetailParser')
const galleryPreviewSetParser = require('./../parser/galleryPreviewSetParser')
const whatsHotParser = require('./../parser/galleryWhatsHotParser')
const crypto = require('crypto')
const secret = 'Cytusian'
const Models = require('./../models')
const moment = require('moment')
const jwt = require('jwt-simple')
const formidable = require('formidable')
const jAuth = require('./jAuth')
var mime = require('mime')
function getHost (isEX) {
  let isEx = null
  if (isEX === 'true') {
    isEx = true
  } else {
    isEx = false
  }
  if (isEx) {
    return 'https://exhentai.org'
  } else {
    return 'https://e-hentai.org'
  }
}

/** const getProxyIp = () => {
  return new Promise((resolve, reject) => {
    fetch
    .get({
      url: 'http://localhost:8000/?count=150&protocol=0',
      headers: {
        'Content-type': 'application/json'
      },
      json: true
    }, (err, httpResponse, body) => {
      if (err) {
        reject(err)
        return
      }
      resolve(body)
    })
  })
}
getProxyIp().then((data) => {
  console.log(data[0])
  const ip = 'http://' + data[0][0] + ':' + data[0][1]
  fetch.get({
    url: 'https://e-hentai.org',
    headers: {
      'accept': 'text/html, application/xhtml+xml, image/jxr',
      'accept-language': 'zh-CN,zh;q=0.8',
      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
    },
    proxy: ip,
    tunnel: false
  }, (err, httpResponse, body) => {
    console.log(httpResponse)
    console.log('err:' + err)
    console.log(body)
  })
})**/
const getGalleryList = (params, isEX) => {
  return new Promise((resolve, reject) => {
    request
      .get(`${getHost(isEX)}/${params}`)
      .set('Cookie', 'ipb_member_id=1832958; ipb_pass_hash=b5f7a26f189f431c53415535f9968a96; igneous=20693e940; lv=1490853014-1490860998; nw=1')
      .set('Accept', 'text/html, application/xhtml+xml, image/jxr, */*')
      .end((err, res) => {
        if (err) {
          reject(new Error('GETLISTERROR'))
        } else {
          resolve(res.text)
        }
      })
  })
}

const getWhatsHot = () => {
  return new Promise((resolve, reject) => {
    request
      .get('https://e-hentai.org/')
      .set('Cookie', 'ipb_member_id=1832958; ipb_pass_hash=b5f7a26f189f431c53415535f9968a96; igneous=20693e940; lv=1490853014-1490860998; nw=1')
      .set('Accept', 'text/html, application/xhtml+xml, image/jxr, */*')
      .end((err, res) => {
        if (err) {
          reject(new Error('GETWHATSHOTERR'))
        } else {
          resolve(res.text)
        }
      })
  })
}

const getGalleryDetail = (params) => {
  let gid = params.gid
  let token = params.token
  let pageNo = params.pageNo || 1
  let isEX = params.isEX
  return new Promise((resolve, reject) => {
    request
      .get(`${getHost(isEX)}/g/${gid}/${token}/?p=${pageNo - 1}`)
      .set('Cookie', 'ipb_member_id=1832958; ipb_pass_hash=b5f7a26f189f431c53415535f9968a96; s=bf28c65a3; igneous=20693e940; lv=1490853014-1490861498; uconfig=xr_2400-ts_l; nw=1')
      .end((err, res) => {
        if (err) {
          reject(new Error('GETDETAILERROR'))
        } else {
          resolve(res.text)
        }
      })
  })
}

const getGalleryShowKey = (url) => {
  return new Promise((resolve, reject) => {
    request.get(url)
      .set('Cookie', 'ipb_member_id=1832958; ipb_pass_hash=b5f7a26f189f431c53415535f9968a96; s=bf28c65a3; igneous=20693e940; lv=1490853014-1490861498; uconfig=xr_2400-ts_l; nw=1')
      .set('Accept', 'text/html, application/xhtml+xml, image/jxr, */*')
      .end((err, res) => {
        if (err) {
          reject(new Error('GETSHOWKEYERROR'))
        } else {
          resolve(res.text)
        }
      })
  })
}

const galleryListstart = async (params, isEX) => {
  try {
    let result = await getGalleryList(params, isEX)
    let gallleryList = galleryListParser(result)
    return gallleryList
  } catch (err) {
    throw new Error(err.message)
  }
}

const galleryDetailStart = async (params) => {
  try {
    let result = await getGalleryDetail(params)
    let galleryDetail = null
    if (!params.pageNo) {
      galleryDetail = galleryDetailParser(result)
    } else {
      galleryDetail = galleryPreviewSetParser(result)
    }
    return galleryDetail
  } catch (err) {
    throw new Error(err.message)
  }
}

const galleryWhatsHotStart = async () => {
  try {
    let result = await getWhatsHot()
    let whatsHot = whatsHotParser(result)
    return whatsHot
  } catch (err) {
    throw new Error(err.message)
  }
}

router.all('/api/*', [jAuth])

router.get('/api/e-gallery', (req, res) => {
  let params = req._parsedUrl.search
  let pageId = req.query.page
  let isEX = req.query.isEX
  galleryListstart(params, isEX).then(function (data) {
    res.json({status: 'OK', payload: Object.assign({page: pageId}, data), userInfo: req.userInfo})
  }).catch((e) => {
    res.json({status: 'ERROR', payload: e.message})
  })
})

router.get('/api/galleryDetail/:gid/:token', (req, res) => {
  let gid = req.params.gid
  let token = req.params.token
  let pageNo = req.query.pageNo || 0
  let isEX = req.query.isEX || false
  galleryDetailStart({gid, token, pageNo, isEX}).then((data) => {
    res.json({status: 'OK', payload: data, userInfo: req.userInfo})
  }).catch((e) => {
    res.json({status: 'ERROR', payload: e.message})
  })
})

router.get('/api/galleryKey', (req, res) => {
  let showKey = null
  let showReg = new RegExp("var showkey=\"([a-z0-9]+)\";")
  let url = req.query.url
  getGalleryShowKey(url).then((result) => {
    if (!showReg.test(result)) {
      res.json({status: 'ERROR', payload: 'GETSHOWKEYFAIL'})
      return
    }
    showKey = result.match(showReg)
    res.json({status: 'OK', payload: showKey[1], userInfo: req.userInfo})
  }).catch((e) => {
    res.json({status: 'ERROR', payload: e.message})
  })
})

router.get('/api/whatsHot', (req, res) => {
  galleryWhatsHotStart().then(result => {
    res.json({status: 'OK', payload: result, userInfo: req.userInfo})
  }).catch(e => {
    res.json({status: 'ERROR', payload: e.message})
  })
})

router.get('/api/preserveLoginStatus', (req, res) => {
  console.log(req.userInfo)
  res.json({status: 'OK', userInfo: req.userInfo})
})

router.post('/register', (req, res) => {
  let form = new formidable.IncomingForm({
    uploadDir: 'static/upload/avatar',
    encoding: 'utf-8',
    keepExtensions: true
  })
  form.parse(req, (err, fields, files) => {
    let username = fields.username
    let password = fields.password
    let avatarPath = files.avatar.path
    Models.UsersModel.findOne({username: username}, function (err, user) {
      if (err) {
        fs.unlink(avatarPath)
        res.json({status: 'ERROR', payload: 'SERVERERROR'})
        return
      }
      if (user) {
        fs.unlink(avatarPath)
        res.json({status: 'ERROR', payload: 'USEREXISTS'})
        return
      }
      let encryptedPassword = crypto.createHmac('sha256', secret)
                     .update(password)
                     .digest('hex')
      let avatarExt = mime.extension(files.avatar.type)
      let fileName = username + new Date().getTime() + '.' + avatarExt
      fs.rename(avatarPath, 'static/upload/avatar/' + fileName + '', function (err) {
        if (err) {
          res.json({status: 'ERROR', payload: 'UPLOADFAIL'})
          console.log(err)
          return
        }
        let registerUser = new Models.UsersModel({username: username, password: encryptedPassword, avatar: 'upload/avatar/' + fileName + ''})
        registerUser.save(function (err, row) {
          if (err) {
            res.json({status: 'ERROR', payload: 'SERVERERROR'})
            return
          }
          res.json({status: 'OK', payload: 'REGISTERSUCCESS'})
        })
      })
    })
  })
})

router.post('/login', (req, res) => {
  let username = req.body.username
  let password = req.body.password
  let encryptedPassword = crypto.createHmac('sha256', secret)
                   .update(password)
                   .digest('hex')
  Models.UsersModel.findOne({username: username}, function (err, user) {
    if (err) {
      res.json({status: 'ERROR', payload: 'SERVERERROR'})
      return
    }
    if (!user) {
      res.json({status: 'ERROR', payload: 'USERNOTEXISTS'})
      return
    }
    if (encryptedPassword !== user.password) {
      res.json({status: 'ERROR', payload: 'PASSWORDERROR'})
      return
    }
    let expires = moment().add(7, 'days').valueOf()
    let token = jwt.encode({
      iss: user.username,
      exp: expires
    }, 'WTMSB')
    res.json({status: 'OK', payload: {avatar: user.avatar, username: user.username, token}})
  })
})

module.exports = router
